package org.example.security.auth.config.authorize;

import org.springframework.context.annotation.Lazy;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;

import javax.annotation.Resource;

/**
 * 用于浏览器授权
 */
@EnableAuthorizationServer
//@Configuration
public class AuthorizationServerConfigUseImplicit extends AuthorizationServerConfigurerAdapter {

    @Resource
    @Lazy
    private PasswordEncoder passwordEncoder;

    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        // 允许表单认证
        security.allowFormAuthenticationForClients();
    }

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        /*
            简化模式：implicit
            1、应用：发起授权请求  http://localhost:8080/oauth/authorize?response_type=token&client_id=client&redirect_uri=http://www.baidu.com&scope=all
            2、用户：登陆授权中心
            3、用户：同意授权
            4、授权中心：通过redirect_uri回调应用，并带上access_token参数  https://www.baidu.com/#access_token=a2756e7a-78e9-4e50-8d79-37c3eb998b66&token_type=bearer&expires_in=3599
            5、应用：带上access_token从资源服务获取资源   http://localhost:8080/user/current?access_token=a2756e7a-78e9-4e50-8d79-37c3eb998b66
        */

        clients.inMemory()
                .withClient("client")
                .secret(passwordEncoder.encode("123456"))
                .redirectUris("http://www.baidu.com")
                .accessTokenValiditySeconds(3600)
                .refreshTokenValiditySeconds(86400)
                .scopes("all")
                // .autoApprove(true)
                .authorizedGrantTypes("implicit");
    }
}
